const logger = require('./console-logger')
const xml2js = require('xml2js')
const cache = require('./cache.js')
const { doRequest } = require('./http-utils')

async function rss(url, params={}) {
    const keyword = params.keyword ? params.keyword : ''
    url = url.replace('${keyword}', keyword)

    const cacheKey = `rss_${url}`;
    let data = cache.get(cacheKey) || [];
    logger.debug('rss cacheKey: ', cacheKey, cache.exists(cacheKey));
    if (!data || data.length === 0) {
        try {
            const response = await doRequest({
                url,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.27'
                }
            })
            
            const parser = new xml2js.Parser(/* options */);
            const result = await parser.parseStringPromise(response)
            if (result && result.rss && result.rss.channel[0] && result.rss.channel[0].item) {
                data = result.rss.channel[0].item.map(o => {
                    const category = matchCategory(o.category[0]._)
                    const address = o.enclosure[0].$.url
                    return {
                        title: o.title[0],
                        link: o.link[0], // 详情地址
                        description: o.description[0],
                        author: o.author[0],
                        category,
                        mediaType: category2mediaType(category),
                        comments: o.comments[0], // 种子评论
                        address: address ? decodeURI(address) : '', // 下载地址
                        size: o.enclosure[0].$.length,
                        hash: o.guid[0]._, 
                        pubDate: o.pubDate[0]
                    }
                })
                cache.set(cacheKey, data, 60);
            }
        } catch (e) {
            logger.error(e.message);
        }
    }
    return data
}

async function jackett(url, apiKey, params={}) {
    const baseUrl = `${url}/api/v2.0/indexers/all/results?apikey=${apiKey}&Query=${params.keyword}`;
    const cacheKey = `jackett_${baseUrl}`;
    let data = cache.get(cacheKey) || {Results:[], Indexers:[]};
    logger.debug('jackett cacheKey: ', cacheKey, cache.exists(cacheKey));
    if (!data || data.Results.length === 0) {
        try {
            const response = await doRequest({
                url: baseUrl
            })
            // console.log('jackett', response);
            if (response) {
                data = response;
                data.Results.forEach(row => {
                    const category = matchCategory(row.CategoryDesc)
                    row.CategoryMap = category
                    row.mediaType = category2mediaType(category)
                })
                cache.set(cacheKey, data, 60);
            }
        } catch (e) {
            logger.error(e.message);
        }
    }
    return data
}

// 站点分类转化为系统可识别分类
// TODO 分类匹配规则动态配置
function matchCategory(val) {
    // 0: {id: 1, name: "电影", folder: "Movies", description: null}
    // 1: {id: 2, name: "连续剧", folder: "TV-Series", description: ""}
    // 2: {id: 3, name: "动漫", folder: "Animation", description: null}
    // 3: {id: 4, name: "记录片", folder: "Documentary", description: null}
    // 4: {id: 5, name: "综艺", folder: "TV-Show", description: null}
    // 5: {id: 6, name: "软件", folder: "Software", description: null}
    // 6: {id: 7, name: "资料", folder: "Education", description: null}
    // 7: {id: 8, name: "游戏", folder: "Game", description: null}
    // 8: {id: 9, name: "音乐", folder: "Music", description: null}
    // 9: {id: 10, name: "体育", folder: "Sports", description: null}
    // 10: {id: 11, name: "其它", folder: "Other", description: null}
    // 11: {id: 12, name: "18+", folder: "Sex", description: null}

    // btschool, hddolby, m-team
    if (arrayIndexOf(['电视剧', '连续剧/TV-Series', 'TV Series电视剧', 'TV Series(影劇/綜藝)', 'TV'], val)) {
        return 'TV-Series'
    } else if (arrayIndexOf(['电影', '电影/Movies', 'Movies电影', 'Movie(電影)', 'Movies'], val)) {
        return 'Movies'
    } else if (arrayIndexOf(['动漫', '动漫/Animation', 'Animations动漫', 'Anime(動畫)', 'TV/Anime', 'Anime'], val)) {
        return 'Animation'
    } else if (arrayIndexOf(['纪录片', '纪录片/Documentary', 'Documentaries纪录片', '紀錄教育'], val)) {
        return 'Documentary'
    } else if (arrayIndexOf(['综艺', '综艺/TV-Show', 'TV Shows综艺', 'TV Series(影劇/綜藝)'], val)) {
        return 'TV-Show'
    } else if (arrayIndexOf(['软件', '软件/Software', '-', 'Software(軟體)'], val)) {
        return 'Software'
    } else if (arrayIndexOf(['资料', '资料/Education', 'Study学习', 'eBook(電子書)'], val)) {
        return 'Education'
    } else if (arrayIndexOf(['游戏', '游戏/Game', 'Games游戏', 'PCGame(PC遊戲)'], val)) {
        return 'Game'
    } else if (arrayIndexOf(['音乐', '音乐/Music', 'HQ Audio音乐', 'Music(AAC/ALAC)'], val)) {
        return 'Music'
    } else if (arrayIndexOf(['体育', '体育/Sports', 'Sports体育', 'Sports(運動)'], val)) {
        return 'Sports'
    } else if (arrayIndexOf(['AV'], val)) { // m-team中分类数据行不同，未解析
        return 'Sex'
    } else {
        return 'Other'
    }
}
function arrayIndexOf(array, val) {
    for (let index = 0; index < array.length; index++) {
        if (val.indexOf(array[index]) >= 0) {
            return true
        }
    }
    return false
}

function category2mediaType(category) {
    if(['Movies'].includes(category)) {
        return 'movie'
    } else if(['TV-Series', 'Animation', 'TV-Show', 'Documentary'].includes(category)) {
        // TODO 有些站点 Animation可能为动画电影
        return 'tv'
    } else {
        return 'other'
    }
}

module.exports = {
    rss, jackett
}